package com.cooper.controllers;

import java.lang.annotation.Annotation;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.portal.Portal;

import com.google.common.collect.Maps;

public class TemplateInterceptor extends ControllerInterceptorAdapter {
	
	@Override
    public Class<? extends Annotation> getRequiredAnnotationClass() {
        return Template.class;
    }
	
	@Override
    public Object before(Invocation inv) throws Exception {
        Object[] methodParams = inv.getMethodParameters();
		Portal portal = null;
		for(Object obj: methodParams){
			if(obj instanceof Portal){
				portal = (Portal) obj;
				break;
			}
		}
		if(null != portal){
			if(!"true".equals(String.valueOf(inv.getParameter("_useTemplate")))){
				String requestUrl = inv.getRequestPath().getUri();
				Map<String, String> paramMap = Maps.newConcurrentMap();
				paramMap.put("_useTemplate", "true");
				if("GET" == inv.getRequest().getMethod()){
					paramMap.putAll(this.getParameters(inv.getRequest()));
				}
				portal.addWindow("template", this.generateUrl(requestUrl, paramMap));
				
				Template template = inv.getAnnotation(Template.class);
				if(null != template){
					inv.addModel("_pageTitle", template.title());
				}
				return "f:/template";
			}
		}
        return true;
    }
	
	private String generateUrl(String requestUrl, Map<String, String> paramMap){
		StringBuffer buffer = new StringBuffer(requestUrl);
		boolean hasParams = requestUrl.contains("?");
		int index = 0;
		for(Entry<String, String> entry: paramMap.entrySet()){
			if(0 == index && !hasParams){
				buffer.append("?");
			} else {
				buffer.append("&");
			}
			buffer.append(entry.getKey()).append("=").append(entry.getValue());
			index ++;
		}
		return buffer.toString();
	}
	
	@SuppressWarnings("rawtypes")
	private Map<String, String> getParameters(HttpServletRequest request){
		Map<String, String> retMap = Maps.newConcurrentMap();
		Enumeration paramNames = request.getParameterNames();
		while(paramNames.hasMoreElements()){
			String paramName = (String)paramNames.nextElement();
			retMap.put(paramName, request.getParameter(paramName));
		}
		return retMap;
	}
	
}
